﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Entity;
using Kelper.Domain.Models;
using Kelper.Domain.Data.Abstract;

namespace Kelper.Domain.Data
{
    public class CategoryRepository : ICategoryRepository
    {
        private KelperDbContext db;

        public CategoryRepository(KelperDbContext db)
        {
            this.db = db;
        }

        public IQueryable<Category> Categories
        {
            get { return db.Categories; }
        }

        public void Remove(string name)
        {
            Category category = db.Categories
                .Include(c => c.Recipes).FirstOrDefault(c => c.Name == name);
            if (category != null)
            {
                db.Categories.Remove(category);
                db.SaveChanges();
            }
        }

        public void Rename(string oldName, string newName)
        {
            Category category = Categories.FirstOrDefault(c => c.Name == oldName);
            if (category != null)
            {
                category.Name = newName;
                db.Entry(category).State = EntityState.Modified;
                db.SaveChanges();
            }
        }

        public void Add(string name)
        {
            Category nameTaken = Categories.FirstOrDefault(c => c.Name == name);

            if (nameTaken == null)
            {
                db.Categories.Add(new Category { Name = name });
                db.SaveChanges();
            }
        }
    }
}
